/**
 * 
 */
package com.hfjyz.exam.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hfjyz.exam.contants.ExamContants;

/**
 *
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private String adminLoginUrl;

	private String loginUrl;
	private List<String> adminUrls;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle
	 * (javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String reqUrl = request.getRequestURI();
		if (reqUrl.contains(loginUrl) || reqUrl.contains(adminLoginUrl)) {
			return true;
		}
		if (adminUrls != null && adminUrls.size() > 0) {
			for (String url : adminUrls) {
				if (reqUrl.contains(url)) {
					if (request.getSession().getAttribute("AdminInfo") == null) {
						request.getRequestDispatcher(adminLoginUrl).forward(
								request, response);
						return false;
					} else {
						return super.preHandle(request, response, handler);
					}
				}
			}
		}
		if (request.getSession().getAttribute(
				ExamContants.SESSION_KEY_LOGIN_INFO) == null) {
			request.getRequestDispatcher(loginUrl).forward(request, response);
			return false;
		}
		return super.preHandle(request, response, handler);
	}

	/**
	 * @return the loginUrl
	 */
	public String getLoginUrl() {
		return loginUrl;
	}

	/**
	 * @param loginUrl
	 *            the loginUrl to set
	 */
	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	/**
	 * @return the adminLoginUrl
	 */
	public String getAdminLoginUrl() {
		return adminLoginUrl;
	}

	/**
	 * @param adminLoginUrl
	 *            the adminLoginUrl to set
	 */
	public void setAdminLoginUrl(String adminLoginUrl) {
		this.adminLoginUrl = adminLoginUrl;
	}

	public List<String> getAdminUrls() {
		return adminUrls;
	}

	public void setAdminUrls(List<String> adminUrls) {
		this.adminUrls = adminUrls;
	}

}
